import React, {
    PureComponent
} from 'react';

import {
    Image,
    TouchableWithoutFeedback
} from 'react-native';


import * as Animated from 'react-native-animatable';

interface Props {
    style?: any,
    source?: number,
    type: Animated.Animation|null,
    onPress: Function,
    value:any,
    duration:number,
    disabled:boolean
}

class Press extends PureComponent<Props> {
    static defaultProps = {
        value:``,
        type: `fadeIn`,
        onPress:() => null,
        duration:500,
        disabled:false
    }

    pressIn:boolean=false;
    pressTimeout:any = null

    animate: any = null;

    _onPressIn = () => {
        const {
            type,
            duration,
            disabled
        } = this.props;

        if (type && !disabled) {
            this.animate.animate(type, duration);
        }
    }

    renderImage = (source: number) => {
        return (
            <Image source={source} />
        )
    }

    setPressRest = () => {
        this.pressTimeout = (
            setTimeout(() => {
                this.pressIn = false;
            },500)
        )
    }


    onPress = () => {
        const {
            onPress,
            value,
            disabled
        } = this.props;

        if(disabled) {
           return false
        }

        if(this.pressIn) {
            return false
        }

        this.pressIn = true;
        this.setPressRest();

        onPress(value);
    }

    componentWillUnmount() {
        if(this.pressTimeout) {
            clearTimeout(this.pressTimeout)
        }
    }

    render() {
        const {
            style,
            source,

            children
        } = this.props;
        return (
            <TouchableWithoutFeedback
                onPress={this.onPress}
                onPressIn={this._onPressIn}
            >
                <Animated.View
                    delay={0}
                    style={style}
                    ref={e => this.animate = e}
                >
                    {!!source ? this.renderImage(source) : children}
                </Animated.View>
            </TouchableWithoutFeedback>
        )
    }
}

export default Press;